package cn.lu.joke.util;

import android.support.v4.app.Fragment;

import java.util.HashMap;
import java.util.Map;

import cn.lu.joke.base.BaseFragment;

public class FragmentManager {

    private Map<Class<?>, Fragment> mFragmentMap;
    private FragmentManager(){
        mFragmentMap = new HashMap<>();
    }

    private static class Holder{
        private static final FragmentManager INSTANCE = new FragmentManager();
    }

    public static FragmentManager get() {
        return Holder.INSTANCE;
    }

    public void addFragment(Fragment fragment) {
        mFragmentMap.put(fragment.getClass(), fragment);
    }

    public void removeFragment(Class classz) {
        if (mFragmentMap.containsKey(classz)) {
            mFragmentMap.remove(classz);
        }
    }

    public void removeFragment(Fragment fragment) {
        if (mFragmentMap.containsValue(fragment)) {
            mFragmentMap.remove(fragment);
        }
    }

    @SuppressWarnings("unchecked")
    public <T extends BaseFragment> T getFragment(Class<T> classz) {
        Fragment ft = mFragmentMap.get(classz);
        if (ft != null) {
            return (T) ft;
        }
        return null;
    }

}
